package com.example.myapplication.ui.home;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.myapplication.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.SensorInfo;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.NCallBack;
import cn.com.newland.nle_sdk.util.NetWorkBusiness;
import retrofit2.Call;
import retrofit2.Response;

public class HomeFragment extends Fragment {
    private String accessToken = "8AEDE434D56DB7E31D0568CB739F0B114F2888E9D26BC85BB87406A8B94370DAA4B362AEF1E216EE06A2A88B3E67D5A7DD94EBDDDC43D74D81BDFB896C9D511A871D45490AB98E1AAF3733050EF5520BE55A55AD6C2A1F14886F1D428CAA6E2FC2CD613F2E6F4E821468598CEE4A459C82C8B001D68FFDB47657B15B95549D82C0B0E895BFE0AA5CC5F6DD2425EFCB7C93F60EE4463E65E43F19AEF6DB4E2501853CFCB501E50A835C0B2FACC7C4204B8B2102153ABAF19745DAFE2281E56A4AC5A7231CA9F49F4934A8CA8C0D8D7423AF9D4AC929B2DC026D47DDDAFE077298";
    private String baseUrl = "https://api.nlecloud.com";
    private NetWorkBusiness netWorkBusiness;
    private String deviceId = "1276366";
    private VideoView chuanglian2;
    private ImageView deng1, fenshang1;
    private String videoPath1, videoPath2;
    private TextView temperatureText, humidityText, lightText;
    private Switch fanSwitch, Switchdengpao;
    private Button chuangliangoff, chuangliangopen;
    private boolean isRunning = true;
    private final Handler handler = new MyHandler(this);

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        // 初始化网络业务对象
        netWorkBusiness = new NetWorkBusiness(accessToken, baseUrl);

        // 加载布局文件
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        // 初始化视图
        initViews(view);

        // 登录
        signIn();

        // 启动数据更新线程
        startDataUpdateThread();

        return view;
    }

    private void initViews(View view) {
        temperatureText = view.findViewById(R.id.temperature);
        humidityText = view.findViewById(R.id.humidity);
        lightText = view.findViewById(R.id.light);
        chuanglian2 = view.findViewById(R.id.chuanglian2);
        deng1 = view.findViewById(R.id.deng1);
        fenshang1 = view.findViewById(R.id.fengshang1);
        Switchdengpao = view.findViewById(R.id.switchdengpao);
        chuangliangoff = view.findViewById(R.id.chuanglianoff);
        chuangliangopen = view.findViewById(R.id.chuanglianopen);

        // 初始化Switch控件并设置监听器
        fanSwitch = view.findViewById(R.id.fan);
        fanSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                fenshang1.setImageResource(R.drawable.fenshangzhuang);
                fan_ON();
            } else {
                fenshang1.setImageResource(R.drawable.fenshang);
                fan_OFF();
            }
        });

        // 设置其他控件的监听器
        Switchdengpao.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // 灯开关控制逻辑
            if (isChecked) {
                deng1.setImageResource(R.drawable.dengliang);
                light_ON();
            } else {
                deng1.setImageResource(R.drawable.dengmie);
                light_OFF();
            }
        });

        videoPath1 = "android.resource://" + getActivity().getPackageName() + "/" + R.raw.chuangliank;
        videoPath2 = "android.resource://" + getActivity().getPackageName() + "/" + R.raw.chuangliang;

        chuangliangopen.setOnClickListener(v -> curtain_OPEN());
        chuangliangoff.setOnClickListener(v -> curtain_CLOSE());
    }

    public void signIn() {
        netWorkBusiness.signIn(new SignIn("17819263754", "123456"), new NCallBack<BaseResponseEntity<User>>(getActivity()) {
            @Override
            public void onFailure(Call<BaseResponseEntity<User>> call, Throwable t) {
                super.onFailure(call, t);
                Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call<BaseResponseEntity<User>> call, Response<BaseResponseEntity<User>> response) {
                super.onResponse(call, response);
                BaseResponseEntity<User> baseResponseEntity = response.body();
                if (baseResponseEntity != null) {
                    if (baseResponseEntity.getStatus() == 0) {
                        accessToken = baseResponseEntity.getResultObj().getAccessToken();
                        netWorkBusiness = new NetWorkBusiness(accessToken, baseUrl); // 更新网络业务的token
                        Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            protected void onResponse(BaseResponseEntity<User> userBaseResponseEntity) {
                // 实现方法
            }
        });
    }

    public void temp() {
        netWorkBusiness.getSensor(deviceId, "m_temperature", new NCallBack<BaseResponseEntity<SensorInfo>>(getActivity()) {
            @Override
            public void onResponse(Call<BaseResponseEntity<SensorInfo>> call, Response<BaseResponseEntity<SensorInfo>> response) {
                super.onResponse(call, response);
                BaseResponseEntity<SensorInfo> baseResponseEntity = response.body();
                if (baseResponseEntity != null) {
                    Gson gson = new Gson();
                    JSONObject jsonObject = null;
                    String msg = gson.toJson(baseResponseEntity);
                    try {
                        jsonObject = new JSONObject(msg);
                        JSONObject resultObj = (JSONObject) jsonObject.get("ResultObj");
                        String value = resultObj.getString("Value");
                        int temp_value = Double.valueOf(value).intValue();
                        temperatureText.setText(temp_value + "℃");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "温度数据解析失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            protected void onResponse(BaseResponseEntity<SensorInfo> sensorInfoBaseResponseEntity) {
                // 实现方法
            }
        });
    }

    public void hum() {
        netWorkBusiness.getSensor(deviceId, "m_humidity", new NCallBack<BaseResponseEntity<SensorInfo>>(getActivity()) {
            @Override
            public void onResponse(Call<BaseResponseEntity<SensorInfo>> call, Response<BaseResponseEntity<SensorInfo>> response) {
                super.onResponse(call, response);
                BaseResponseEntity<SensorInfo> baseResponseEntity = response.body();
                if (baseResponseEntity != null) {
                    Gson gson = new Gson();
                    JSONObject jsonObject = null;
                    String msg = gson.toJson(baseResponseEntity);
                    try {
                        jsonObject = new JSONObject(msg);
                        JSONObject resultObj = (JSONObject) jsonObject.get("ResultObj");
                        String value = resultObj.getString("Value");
                        int hum_value = Double.valueOf(value).intValue();
                        humidityText.setText(hum_value + "%RH");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "湿度数据解析失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            protected void onResponse(BaseResponseEntity<SensorInfo> sensorInfoBaseResponseEntity) {
                // 实现方法
            }
        });
    }

    public void light() {
        netWorkBusiness.getSensor(deviceId, "m_light", new NCallBack<BaseResponseEntity<SensorInfo>>(getActivity()) {
            @Override
            public void onResponse(Call<BaseResponseEntity<SensorInfo>> call, Response<BaseResponseEntity<SensorInfo>> response) {
                super.onResponse(call, response);
                BaseResponseEntity<SensorInfo> baseResponseEntity = response.body();
                if (baseResponseEntity != null) {
                    Gson gson = new Gson();
                    JSONObject jsonObject = null;
                    String msg = gson.toJson(baseResponseEntity);
                    try {
                        jsonObject = new JSONObject(msg);
                        JSONObject resultObj = (JSONObject) jsonObject.get("ResultObj");
                        String value = resultObj.getString("Value");
                        int light_value = Double.valueOf(value).intValue();
                        lightText.setText(light_value + "Lux");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "光照数据解析失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            protected void onResponse(BaseResponseEntity<SensorInfo> sensorInfoBaseResponseEntity) {
                // 实现方法
            }
        });
    }

    public void fan_ON() {
        netWorkBusiness.control(deviceId, "m_fan", 1, new NCallBack<BaseResponseEntity>(getActivity()) {
            @Override
            protected void onResponse(BaseResponseEntity baseResponseEntity) {
                Toast.makeText(getActivity(), "风扇已开启", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void fan_OFF() {
        netWorkBusiness.control(deviceId, "m_fan", 0, new NCallBack<BaseResponseEntity>(getActivity()) {
            @Override
            protected void onResponse(BaseResponseEntity baseResponseEntity) {
                Toast.makeText(getActivity(), "风扇已关闭", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void light_ON() {
        netWorkBusiness.control(deviceId, "dengpao", 1, new NCallBack<BaseResponseEntity>(getActivity()) {
            @Override
            protected void onResponse(BaseResponseEntity baseResponseEntity) {
                Toast.makeText(getActivity(), "灯已开启", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void light_OFF() {
        netWorkBusiness.control(deviceId, "dengpao", 0, new NCallBack<BaseResponseEntity>(getActivity()) {
            @Override
            protected void onResponse(BaseResponseEntity baseResponseEntity) {
                Toast.makeText(getActivity(), "灯已关闭", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void curtain_OPEN() {
        playVideo(chuanglian2, videoPath2);
        netWorkBusiness.control(deviceId, "tuiganqianjin", 1, new NCallBack<BaseResponseEntity>(getActivity()) {
            @Override
            protected void onResponse(BaseResponseEntity baseResponseEntity) {
                Toast.makeText(getActivity(), "窗帘已打开", Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void curtain_CLOSE() {
        playVideo(chuanglian2, videoPath1);
        netWorkBusiness.control(deviceId, "tuiganqianjin", 0, new NCallBack<BaseResponseEntity>(getActivity()) {
            @Override
            protected void onResponse(BaseResponseEntity baseResponseEntity) {
                Toast.makeText(getActivity(), "窗帘已关闭", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void playVideo(VideoView videoView, String path) {
        // 停止所有正在播放的视频
        if (chuanglian2.isPlaying()) chuanglian2.stopPlayback();
        if (chuanglian2.isPlaying()) chuanglian2.stopPlayback();

        // 设置并播放选定的视频
        videoView.setVideoURI(Uri.parse(path));
        videoView.requestFocus();
        videoView.setOnPreparedListener(MediaPlayer::start);
    }

    private static class MyHandler extends Handler {
        private final HomeFragment fragment;

        public MyHandler(HomeFragment fragment) {
            super(Looper.getMainLooper());
            this.fragment = fragment;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 0 && fragment.isAdded()) {
                fragment.temp();
                fragment.hum();
                fragment.light();
            }
        }
    }

    private void startDataUpdateThread() {
        new Thread() {
            @Override
            public void run() {
                while (isRunning && !Thread.currentThread().isInterrupted()) {
                    handler.sendEmptyMessage(0);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }.start();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isRunning = false;
        handler.removeCallbacksAndMessages(null);
    }
}